<template>
  <div class="article-container">
    <!--导航栏-->
    <van-nav-bar class="page-nav-bar" fixed left-arrow title="洋聪头条" @click-left="$router.back()"></van-nav-bar>
    <div class="main-wrap">
      <!--加载中-->
      <div v-if="loading" class="loading-wrap">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!--文章详情-->
      <div v-else-if="article.title" class="article-detail">
        <!--文章标题-->
        <h1 class="article-title">{{article.title}}</h1>
        <!--用户信息-->
        <van-cell class="user-info" center :border="false">
          <van-image class="avatar" slot="icon" round fit="cover" :src="article.aut_photo" />
          <div slot="title" class="user-name">{{article.aut_name}}</div>
          <div slot="label" class="publish-date">{{article.pubdate | relativeTime}}</div>
          <!--关注用户-->
          <!--<van-button v-if="article.is_followed" class="follow-btn follow-w" round size="small" :loading="followLoading" @click="onFollow">已关注</van-button>
          <van-button v-else class="follow-btn" type="info" color="#3296fa" round size="small" icon="plus" :loading="followLoading" @click="onFollow">关注</van-button>-->
          <!--
              模板中的 $event 是事件参数
              当我们传递给子组件的数据既要使用还要修改。
                传递：props
                      :is-followed="article.is_followed"
                修改：自定义事件
                      @update-is_followed="article.is_followed = $event"
                简写方式：在组件上使用 v-model
                  value="article.is_followed"
                  @input="article.is_followed = $event"
                如果需要修改 v-model 的规则名称，可以通过子组件的 model 属性来配置修改
          -->
          <FollowUser v-model="article.is_followed" :user-id="article.aut_id" />
        </van-cell>
        <!--文章内容-->
        <div ref="article-content" class="article-content" v-html="article.content"></div>
        <van-divider>正文结束</van-divider>
        <!--评论列表-->
        <ArticleComment :source="article.art_id" :list="commentList" @onload-success="totalCommentCount = $event.total_count" @reply-click="onReplyClick" />
        <!--底部区域 star-->
        <div class="article-bottom">
          <van-button class="comment-btn" type="default" round size="small" @click="isPostShow = true">写评论</van-button>
          <van-badge name="comment-o" :content="totalCommentCount">
            <van-icon name="comment-o" class="badge-icon" />
          </van-badge>
          <!--<van-icon name="star-o" color="#777" />-->
          <CollectArticle v-model="article.is_collected" :article-id="article.art_id" />
          <!--<van-icon name="good-job-o" color="#777" />-->
          <LikeArticle v-model="article.attitude" :article-id="article.art_id" />
          <van-icon name="share" color="#777"></van-icon>
        </div>
        <!--底部区域 end-->
        <!--发布评论弹窗-->
        <van-popup v-model="isPostShow" position="bottom">
          <CommentPost :target="article.art_id" @post-success="onPostSuccess" />
        </van-popup>
        <!--评论回复弹窗-->
        <van-popup v-model="isReplyShow" position="bottom">
          <!-- 这里使用 v-if 的目的是让组件随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不会重新加载的问题 -->
          <CommentReply v-if="isReplyShow" :comment="replyComment" :article-id="articleId" @close="isReplyShow = false" />
        </van-popup>
        <!--评论回复弹窗-->
      </div>
      <!--加载失败： 404-->
      <div v-else-if="errStatus === 404" class="error-wrap">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!--加载失败：其他未知错误（例如网络原因或服务端异常）-->
      <div v-else class="error-wrap">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="loadArticle">点击重试</van-button>
      </div>
    </div>
  </div>
</template>

<script>
// import { addFollow, deleteFollow } from '@/api/user'
import { getArticleById } from '@/api/article'
import { ImagePreview } from 'vant'
// 关注用户
import FollowUser from '@/components/follow-user/FollowUser'
// 收藏文章
import CollectArticle from '@/components/collect-article/CollectArticle'
// 点赞文章
import LikeArticle from '@/components/like-article/LikeArticle'
// 评论列表
import ArticleComment from './components/ArticleComment.vue'
// 评论弹窗
import CommentPost from './components/CommentPost.vue'
// 评论回复弹窗
import CommentReply from './components/CommentReply.vue'

export default {
  name: 'Article',
  components: {
    FollowUser,
    CollectArticle,
    LikeArticle,
    ArticleComment,
    CommentPost,
    CommentReply
  },
  props: {
    articleId: {
      required: true,
      type: [Number, String, Object]
    }
  },
  data () {
    return {
      article: {}, // 文章详情内容
      loading: true, // 加载中的loading状态
      errStatus: 0, // 失败的状态码
      followLoading: false, // 默认不显示按钮的加载状态
      totalCommentCount: 0, // 评论数量
      isPostShow: false, // 评论弹窗，默认不显示
      isReplyShow: false, // 控制回复的显示状态
      commentList: [], // 评论列表
      replyComment: {} // 当前回复评论对象
    }
  },
  created () {
    this.loadArticle()
  },
  methods: {
    async loadArticle () {
      try {
        const { data } = await getArticleById(this.articleId)
        this.article = data.data
        // 请求成功，关闭loading
        // this.loading = false
        // console.log(data)
        // 初始化图片点击预览 延迟0秒获取DOM
        setTimeout(() => {
          // console.log(this.$refs['article-content'])
          this.perviewImage()
        }, 0)
      } catch (err) {
        if (err.response && err.response.status === 404) {
          this.errStatus = 404
        }
        // this.loading = false
        console.log('获取数据失败', err)
      }
      // 无论成功还是失败，关闭loading
      this.loading = false
    },
    // 文章相册功能
    perviewImage () {
      // 得到所有的img节点
      const articleContent = this.$refs['article-content']
      const imgs = articleContent.querySelectorAll('img')
      const images = []
      // console.log(imgs)
      imgs.forEach((img, index) => {
        images.push(img.src)
        img.onclick = () => {
          ImagePreview({
            images, // 预览的图片地址数组
            startPosition: index // 起始位置，从0开始
          })
        }
      })
      // console.log(images)
    },
    // 文章评论
    onPostSuccess (data) {
      // 将发布内容显示到列表顶部
      this.commentList.unshift(data.new_obj)
      // 更新评论的总数量
      this.totalCommentCount++
      // 关闭弹窗
      this.isPostShow = false
    },
    // 评论回复
    onReplyClick (comment) {
      console.log('onReplyClick', comment)
      this.replyComment = comment
      // 展示回复内容
      this.isReplyShow = true
    }
    // 关注和取消
    /* async onFollow () {
      this.followLoading = true // 按钮显示加载状态
      try {
        if (this.article.is_followed) {
          // 已关注，取消关注
          const { data } = await deleteFollow(this.article.aut_id)
          console.log(data)
          // this.article.is_followed = false // 已关注，按钮显示已关注
        } else {
          // 没有关注，添加关注
          const { data } = await addFollow(this.article.aut_id)
          console.log(data)
          // this.article.is_followed = true // 未关注，按钮显示未关注
        }
        this.article.is_followed = !this.article.is_followed // 关注已否，按钮显示已关注/未关注
      } catch (err) {
        let message = '操作失败，请稍后重试！'
        if (err.response && err.response.status === 401) {
          message = '请登录后再关注！'
          this.$router.push('/login')
        }
        this.$toast(message)
      }
      this.followLoading = false // 按钮不显示加载状态
    } */
  }
}
</script>

<style scoped lang="less">
.article-container{
  width: 100%;
  padding-top: 46px;
  padding-bottom: 50px;
  background-color: #fff;
  /deep/ .van-nav-bar .van-icon{
    color: #666;
  }
  .article-detail{
    .article-title{
      font-size: 22px;
      font-weight: bold;
      color: #333;
      padding: 0 16px;
    }
    .avatar{
      width: 50px;
      height: 50px;
      margin-right: 5px;
    }
    /deep/ .article-content{
      padding: 16px 16px 0 16px;
      font-size: 16px;
      color: #333;
      word-break: break-all;
      p{
        margin: 2px 0;
      }
      pre{
        padding: 16px;
        overflow: auto;
        background-color: #f6f8fa;
        border-radius: 3px;
      }
    }
  }
  .article-bottom{
    width: 100%;
    height: 50px;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 5;
    background-color: #fff;
    border-top: 1px solid #ebedf0;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    .comment-btn{
      width: 140px;
    }
  }
  .error-wrap{
    text-align: center;
    padding: 15px 0;
  }
  .van-icon-comment-o{
    font-size: 22px;
  }
  /deep/ .van-icon-star-o{
    font-size: 20px;
  }
  .liked{
    font-size: 20px;
    padding-left: 0;
  }
  .van-icon-share{
    font-size: 22px;
  }
}
.loading-wrap{
  width: 100%;
  height: calc(100vh - 46px);
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
